from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...service.buss_pub.bill_manage import BillManageService, OperationType, TypeId, Status
from ...service.common import get_condition, get_info, get_current_user_id
import hashlib
import re
import datetime
import uuid
from enum import Enum
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, DataList, get_cur_time
from ...service.mongo_bill_service import MongoBillFilter


class KnowledgeBaseService(MongoService):
    ''' 知识库管理 '''
    KnowledgeBase = 'PT_Knowledge_Base'

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd,inital_password, session):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        self.db_user = db_user
        self.db_pwd = db_pwd
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_server = BillManageService(
            self.db_addr, self.db_port, self.db_name, self.db_user, self.db_pwd,self.inital_password, self.session)
    
    def get_knowledge_list(self, condition, page=None, count=None):
        '''查询申请列表'''
        keys = ['id','word','type']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id').like(values['id'])) & (C('title').like(values['word'])) | (C('keyword').like(values['word'])) & (C('type') == (values['type']))).project({'_id': 0})
        return self.page_query(_filter, self.KnowledgeBase, page, count)
        
    def update_knowledge(self, knowledge):
        # knowledge = ['title','keyword','content','create_person','update_person']
        print(knowledge)
        print(self.KnowledgeBase)
        res = 'fail'
        user_id = get_current_user_id(self.session)
        _filter = MongoBillFilter()
        _filter.match_bill(C('id') == user_id).project({'_id': 0})
        user = self.query(_filter, 'PT_User')[0]
        if 'id' in knowledge.keys():
            knowledge['update_person_id'] = user_id
            knowledge['update_person_name'] = user['name']
            bill_id = self.bill_manage_server.add_bill(OperationType.update.value, TypeId.knowledgeBase.value, knowledge, self.KnowledgeBase)
            if bill_id:
                res = 'Success'
        else:
            knowledge['create_person_id'] = user_id
            knowledge['create_person_name'] = user['name']
            bill_id = self.bill_manage_server.add_bill(OperationType.add.value, TypeId.knowledgeBase.value, knowledge, self.KnowledgeBase)
            if bill_id:
                res = 'Success'
        return res
        
    def del_knowledge(self, id):
        res = 'Fail'
        bill_id = self.bill_manage_server.add_bill(OperationType.delete.value, TypeId.knowledgeBase.value, {'id': id}, self.KnowledgeBase)
        if bill_id:
            res = 'Success'
        return res
        